import * as THREE from 'three'

export function useAnimations() {
  const animations = reactive({})
  const mixers = []
  
  const setupAnimations = (model, animationClips) => {
    const mixer = new THREE.AnimationMixer(model)
    mixers.push(mixer)
    
    animationClips.forEach(clip => {
      animations[clip.name] = clip
    })
  }
  
  const playAnimation = (name, loopMode = THREE.LoopOnce) => {
    const clip = animations[name]
    if (!clip) return
    
    const mixer = mixers.find(m => m.getRoot() === clip.tracks[0].target.root)
    if (!mixer) return
    
    const action = mixer.clipAction(clip)
    action.reset()
    action.setLoop(loopMode, 1)
    action.clampWhenFinished = true
    action.play()
  }
  
  const updateMixers = (delta) => {
    mixers.forEach(mixer => {
      mixer.update(delta)
    })
  }
  
  return {
    setupAnimations,
    playAnimation,
    updateMixers
  }
}